package com.nulldev.util.web.nTubeExtensions.yt_chat_on_ntube;

import static com.nulldev.util.web.nTube.pages.Urlizer.decodeUrlizer;

import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.Map;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.VariableAPI.ArrayUtils;
import com.nulldev.util.io.file.FileUtil;
import com.nulldev.util.web.HttpClient.HttpClient;
import com.nulldev.util.web.HttpClient.HttpResponse;
import com.nulldev.util.web.HttpServer3.Response;
import com.nulldev.util.web.HttpServer3.pages.v3.HttpPage3;
import com.nulldev.util.web.URLUtils.URLQueryParser;
import com.nulldev.util.web.URLUtils.URLQueryParser.URLQueryParserOptions;
import com.nulldev.util.web.URLUtils.URLUtils;

public class YTChatPolymerInjector extends HttpPage3 {

	public YTChatPolymerInjector() {
		super("/proxy/live_chat_polymer");
	}

	private static final String[] ALLOWED_DOMAINS = new String[]
		{ "www.youtube.com", "youtube.com" };

	private static final String NTUBE_OVERRIDE_PAYLOAD = FileUtil.getResourceAsString(YTChatPolymerInjector.class, "ntube-fetch-override.js");

	@SuppressWarnings("resource")
	@Override
	public Response onRequest(final Request request) {
		final Map<String, String> s = URLQueryParser.extract(request.url(), URLQueryParserOptions.PREFER_EXPERIMENTAL,
				(URLUtils.USE_URL_ACCEL_V2 ? null : URLQueryParserOptions.DISABLE_URL_ACCEL), URLQueryParserOptions.DISABLE_DECODING,
				URLQueryParserOptions.TREAT_URL_AS_QUERY);
		if (!s.containsKey("url") && !(s.containsKey("uzm") && s.containsKey("uzc"))) {
			return new Response(400).requestKeepAliveDisable(true);
		} else if (s.containsKey("url") && s.get("url").isEmpty()) {
			return new Response(400).requestKeepAliveDisable(true);
		}
		final String url = decodeUrlizer(request.url());
		if (!ArrayUtils.StringArrayUtils.cardedContains(ALLOWED_DOMAINS, URLUtils.getDomain(url))) {
			return new Response(401).requestKeepAliveDisable(true);
		}
		try {
			final HttpResponse<InputStream> is = HttpClient.getStream().url(url).create();
			final SequenceInputStream combined_input_stream = new SequenceInputStream(createStream(NTUBE_OVERRIDE_PAYLOAD), is.data());
			return new Response(is.status(), combined_input_stream).deferCompression(true).requestKeepAliveDisable(true);
		} catch (Exception e) {
			JVM.errorln(e);
			return fail(503);
		}
	}

}
